/************************************************************************************
* SLTableMaintainer.cpp                                                             *
*                                                                                   *
* Copyright (C) 2011 Varuna L Amachi                                                *
*                                                                                   *
* This program is free software; you can redistribute it and/or modify              *
* it under the terms of the GNU General Public License as published by              *
* the Free Software Foundation; either version 2 of the License, or any             *
* later version.                                                                    *
*                                                                                   *
* This program is distributed in the hope that it will be useful, but               *
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY        *
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for       *
* more details. You should have received a copy of the GNU General Public           *
* License along with this program; if not, write to the Free Software Foundation,   *
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA                       *
*                                                                                   *
*************************************************************************************/

#include "SLTableMaintainer.h"
#include "settings/YampConfig.h"
#include "common/YLog.h"


#include <QSqlQuery>
#include <QDateTime>
#include <QFile>
#include <QDebug>
#include <QSqlError>

SLTableMaintainer::SLTableMaintainer():IDbMaintainer() {
}


bool SLTableMaintainer::maintainCachingTables(QSqlDatabase* database) {
    //These are going to be little bit complex. So needs time.
}


bool SLTableMaintainer::createCollectionTable(QSqlDatabase* database) {
    QString queryString("CREATE TABLE Collection ("
            "trackId    TEXT PRIMERY KEY,"
            "trackPath  TEXT,"
            "trackName  TEXT,"
            "artistName TEXT,"
            "albumName  TEXT,"
            "trackDate  TEXT,"
            "genre      TEXT,"
            "comment    TEXT,"
            "trackNum   INTEGER,"
            "duration   INTEGER,"
            "bitrate    INTEGER,"
            "sampleRate INTEGER,"
            "channels   INTEGER,"
            "rating     INTEGER,"
            "numPlays   INTEGER,"
            "tags       TEXT);");
    return executeQuery(database, queryString);
}


bool SLTableMaintainer::createHistoryTable(QSqlDatabase* database) {
    QString queryString("CREATE TABLE PlayHistory("
            "lastPlayedTime INTEGER,"
            "trackId TEXT trackId"
            ");");
    return executeQuery(database, queryString);
}




bool SLTableMaintainer::createRecentAdditionsTable(QSqlDatabase* database) {
    QString queryString("CREATE TABLE RecentAdditions("
            "addedTime INTEGER,"
            "trackId TEXT trackId"
            ");");
    return executeQuery(database, queryString);
}


bool SLTableMaintainer::createPlaylistInfoTable(QSqlDatabase* database) {
    QString queryString("CREATE TABLE PlaylistInfo("
            "playlistName TEXT PRIMARY KEY,"
            "creationTime INTEGER,"
            "lastModified INTEGER,"
            "rating       INTEGER,"
            "comment      TEXT"
            ");");
    return executeQuery(database, queryString);
}


bool SLTableMaintainer::createPlaylistTable(QSqlDatabase *database) {
    QString queryString("CREATE TABLE Playlists("
            "playlistName TEXT,"
            "trackIndex   INTEGER,"
            "trackId      TEXT trackId"
            ");");
    return executeQuery(database, queryString);
}


bool SLTableMaintainer::createSettingsTable(QSqlDatabase *database) {
    QString queryString("CREATE TABLE Settings("
            "settingKey TEXT PRIMARY KEY,"
            "settingValue TEXT"
            ");");
    return executeQuery(database, queryString);
}


bool SLTableMaintainer::createSchema(QSqlDatabase *database) {
    return createCollectionTable(database) &&
           createHistoryTable(database) &&
           createPlaylistInfoTable(database) &&
           createPlaylistTable(database) &&
           createRecentAdditionsTable(database) &&
           createSettingsTable(database);
}


bool SLTableMaintainer::executeQuery(QSqlDatabase* database, const QString queryString) {
    if(database != NULL) {
        QSqlQuery query(*database);
        return query.exec(queryString);
    }
    QSqlQuery query;
    bool result = query.exec(queryString);
    YLog::logQuery("createSchema", &query);
    return result;
}


QString SLTableMaintainer::dbType() {
    return "QSQLITE";
}

bool SLTableMaintainer::initDb(QString dbName) {
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setHostName("localHost");
    db.setDatabaseName(dbName);
    if (db.open()) {
        QSqlQuery query("SELECT name FROM sqlite_master WHERE type='table' AND name='Collection'");

        if(query.exec() && query.next()) {
            YLog::logInfo("Database initiation succesful");
        }
        else {
            //Database does not exists
            YLog::logInfo("Creating database");
            createSchema();
        }
        return true;
    }
    YLog::logError(db.lastError().text());
    return false;
}

//bool SLTableMaintainer::isDbExists(QString dbName) {
//    QString dbPath = YampConfig::instance()->getStringConfig("setting_dir");
//    QFile dbFile(dbName.append("/").append(dbName).append(".db3"));
//    return dbFile.exists();
//}
